package com.example.mqttdemo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mqttdemo.entity.pojo.SensorData;
import com.example.mqttdemo.entity.pojo.SensorDataPageQuery;
import com.example.mqttdemo.result.PageResult;
import com.example.mqttdemo.result.Result;
import com.example.mqttdemo.service.SensorDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/sensorData")
public class SensorDataController {

    @Autowired
    private SensorDataService sensorDataService;

    /**
     * 分页查询传感器数据
     *
     * @param current             当前页码
     * @param size                每页显示的记录数
     * @param sensorDataPageQuery 传感器数据查询参数
     * @return 设备列表
     */
    @GetMapping("/pageList")
    public PageResult pageSensorDataByDeviceId(@RequestParam(defaultValue = "1") long current, @RequestParam(defaultValue = "10") long size, SensorDataPageQuery sensorDataPageQuery) {
        IPage<SensorData> page = new Page<>(current, size);
        IPage<SensorData> pageList = sensorDataService.pageSensorData(page, sensorDataPageQuery);
        return new PageResult(pageList.getTotal(), pageList.getRecords());
    }

    /**
     * 获取最新的传感器数据
     */
    @GetMapping("/getLatestData/{deviceId}")
    public Result getLatestData(@PathVariable String deviceId) {
        try {
            return Result.success(sensorDataService.getLatestData(deviceId));
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }
}
